<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>案例_分类导航</title>
  <link rel="stylesheet" href="./css/index.css">
</head>

<body>
  <!-- 大容器 -->
  <div class="container">
    <div class="sub-list">
      <div class="item">
        <h3>分类名字</h3>
        <ul>
          <li>
            <a href="javascript:;">
              <img src="http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/img/category%20(9).png" />
              <p>巧克力</p>
            </a>
          </li>
          <li>
            <a href="javascript:;">
              <img src="http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/img/category%20(9).png" />
              <p>巧克力</p>
            </a>
          </li>
          <li>
            <a href="javascript:;">
              <img src="http://zhoushugang.gitee.io/erabbit-client-pc-static/uploads/img/category%20(9).png" />
              <p>巧克力</p>
            </a>
          </li>
        </ul>
      </div>
    </div>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    /**
     * 目标：把所有商品分类“同时”渲染到页面上
     *  1. 获取所有一级分类数据
     *  2. 遍历id，创建获取二级分类请求
     *  3. 合并所有二级分类Promise对象
     *  4. 等待同时成功后，渲染页面
    */

    //1. 获取所有一级分类数据
    axios({
      url: 'http://hmajax.itheima.net/api/category/top'
    }).then(result => {
      // console.log(result)
      //2. 遍历id，创建获取二级分类请求
      const secPromiseList = result.data.data.map(item => {
        return axios({
          url: 'http://hmajax.itheima.net/api/category/sub',
          params: {
            id: item.id  //这里传递的是一级分类id
          }
        })
      })
      console.log(secPromiseList)  //[二级请求Promise对象， 二级请求Promise对象]
      //3. 合并所有二级分类Promise对象
      const p = Promise.all(secPromiseList)
      p.then(result => {
        console.log(result)
        //4.等待同时成功后，渲染页面
        const htmlStr = result.map(item => {
          const dataObj = item.data.data //去除关键数据对象
          return `<div class="item">
            <h3>${dataObj.name}</h3>
            <ul>
              ${dataObj.children.map(item => {
                return `<li>
                          <a href="javascript:;">
                            <img src="${item.picture}" />
                            <p>${item.name}</p>
                          </a>
                        </li>`
              }).join('')}
            </ul>
          </div>`
        }).join('')
        console.log(htmlStr)
        document.querySelector('.sub-list').innerHTML = htmlStr
        
        
      })
    })
  </script>
</body>

</html>